package com.care.controller.weixin;

import com.alibaba.fastjson.JSONObject;
import com.care.author.AuthRequired;
import com.care.controller.vo.JsonResult;
import com.care.dao.mapper.CommunityMapper;
import com.care.dao.mapper.ServiceMapper;
import com.care.dao.mapper.UserMapper;
import com.care.dao.model.Community;
import com.care.dao.model.Service;
import com.care.dao.model.User;
import com.care.service.ServiceInterface;
import com.care.service.SysLogService;
import com.care.utils.page.PageView;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import jakarta.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 小程序端助老服务接口
 */
@RestController
@RequestMapping("api")
public class CommunityServiceApi extends ApiBaseController {
	
	@Autowired
	private ServiceMapper serviceMapper;
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private CommunityMapper communityMapper;
	@Autowired
	private SysLogService logService;

	/**
	 * 查询我的服务列表（老人）
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping("my/service/list")
	@AuthRequired
	public JsonResult shopList(@RequestBody Map<String, Object> reqMap, HttpServletRequest request) {
		PageView<Service> pageView = new PageView<>();
		User user = getCurrUser(request);
		pageView = pageView.startPage(reqMap);
		List<Service> list = serviceMapper.selectElderMyService(user.getUserId(), null, pageView.getFirstResult(), pageView.getMaxresult());
		// 切割图片
		for (Service item : list) {
			if(StringUtils.isNotBlank(item.getPics())) {
				String[] url = item.getPics().split(",");
				List<String> urls = new ArrayList<>();
				for (int i=0; i<url.length; i++) {
					urls.add(url[i]);
				}
				item.setPicList(urls);
			}
		}
		pageView.setRecords(list);
		pageView.setTotalrecord(serviceMapper.selectElderMyServiceCount(user.getUserId(), null));//总记录数
		return JsonResult.success(pageView);
	}

	/**
	 * 志愿者查看服务列表（所有老人发布的待接单服务）
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping("service/list")
	public JsonResult allServiceList(@RequestBody Map<String, Object> reqMap, HttpServletRequest request) {
		PageView<Service> pageView = new PageView<>();
		pageView = pageView.startPage(reqMap);
		List<Service> list = serviceMapper.selectElderMyService(null, 0, pageView.getFirstResult(), pageView.getMaxresult());
		// 切割图片
		for (Service item : list) {
			if(StringUtils.isNotBlank(item.getPics())) {
				String[] url = item.getPics().split(",");
				List<String> urls = new ArrayList<>();
				for (int i=0; i<url.length; i++) {
					urls.add(url[i]);
				}
				item.setPicList(urls);
			}
		}
		pageView.setRecords(list);
		pageView.setTotalrecord(serviceMapper.selectElderMyServiceCount(null, 0));//总记录数
		return JsonResult.success(pageView);
	}

	/**
	 * 服务详情
	 * @param sid
	 * @return
	 */
	@RequestMapping("service/detail")
	public JsonResult detail(@RequestParam Integer sid) {
		JsonResult result = new JsonResult(true, "0", "查询成功");
		Service service = serviceMapper.selectByPrimaryKey(sid);
		// 切割图片、标签
		if(StringUtils.isNotBlank(service.getPics())) {
			String[] url = service.getPics().split(",");
			List<String> urls = new ArrayList<>();
			for (int i=0; i<url.length; i++) {
				urls.add(url[i]);
			}
			service.setPicList(urls);
		}
		service.setPublishUser(userMapper.selectByPrimaryKey(service.getUserId()));
		if(service.getStatus()>ServiceInterface.SERVICE_STATUS_WAIT){
			service.setVolunteer(userMapper.selectByPrimaryKey(service.getAcceptUserId()));
		}
		result.setData(service);
		return result;
	}

	/**
	 * 老人发布服务请求
	 * @param req
	 * @param request
	 * @return
	 */
	@RequestMapping("service/save")
	@AuthRequired
	public JsonResult saveService(@RequestBody JSONObject req, HttpServletRequest request){
		User user = getCurrUser(request);
		Service service = JSONObject.parseObject(req.toJSONString(), Service.class);
		service.setUserId(user.getUserId());
		service.setPublishTime(new Date());
		service.setCommunityId(user.getCommunityId());
		serviceMapper.insertSelective(service);
		JsonResult jsonResult = new JsonResult();
		jsonResult.setData(service);
		logService.publishServiceLog(service, user);
		return jsonResult;
	}

	/**
	 * 志愿者接单
	 * @param req
	 * @param request
	 * @return
	 */
	@RequestMapping("service/accept")
	@AuthRequired
	public JsonResult acceptService(@RequestBody JSONObject req, HttpServletRequest request){
		User user = getCurrUser(request);
		Integer serviceId = req.getInteger("serviceId");
		Service service = serviceMapper.selectByPrimaryKey(serviceId);
		service.setStatus(ServiceInterface.SERVICE_STATUS_PROCESSING);//进行状态
		service.setAcceptUserId(user.getUserId());
		service.setAcceptTime(new Date());
		serviceMapper.updateByPrimaryKeySelective(service);
		JsonResult jsonResult = new JsonResult();
		jsonResult.setData(service);
		logService.updateServiceLog(service, ServiceInterface.SERVICE_STATUS_PROCESSING, user);
		return jsonResult;
	}

	/**
	 * 老人：取消服务
	 * @param req
	 * @param request
	 * @return
	 */
	@RequestMapping("service/cancel")
	@AuthRequired
	public JsonResult cancelService(@RequestBody JSONObject req, HttpServletRequest request){
		Integer serviceId = req.getInteger("serviceId");
		User user = getCurrUser(request);
		Service service = serviceMapper.selectByPrimaryKey(serviceId);
		service.setStatus(ServiceInterface.SERVICE_STATUS_CANCEL);//取消状态
		serviceMapper.updateByPrimaryKeySelective(service);
		JsonResult jsonResult = new JsonResult();
		jsonResult.setData(service);
		logService.updateServiceLog(service, ServiceInterface.SERVICE_STATUS_CANCEL, user);
		return jsonResult;
	}

	/**
	 * 老人：服务完成确认状态
	 * @param req
	 * @param request
	 * @return
	 */
	@RequestMapping("service/finish")
	@AuthRequired
	public JsonResult finishService(@RequestBody JSONObject req, HttpServletRequest request){
		Integer serviceId = req.getInteger("serviceId");
		User user = getCurrUser(request);
		Service service = serviceMapper.selectByPrimaryKey(serviceId);
		service.setStatus(ServiceInterface.SERVICE_STATUS_FINISH);//完成状态
		service.setFinishTime(new Date());
		serviceMapper.updateByPrimaryKeySelective(service);
		JsonResult jsonResult = new JsonResult();
		jsonResult.setData(service);
		logService.updateServiceLog(service, ServiceInterface.SERVICE_STATUS_FINISH, user);
		return jsonResult;
	}

	/**
	 * 老人：服务反馈
	 * @param req
	 * @param request
	 * @return
	 */
	@RequestMapping("service/feedback")
	@AuthRequired
	public JsonResult feedbackService(@RequestBody JSONObject req, HttpServletRequest request){
		Integer serviceId = req.getInteger("serviceId");//
		User user = getCurrUser(request);
		Service service = serviceMapper.selectByPrimaryKey(serviceId);
		service.setFeedbackRate(req.getInteger("rate"));//反馈评分
		service.setFeedback(req.getString("feedback"));//反馈内容
		service.setStatus(ServiceInterface.SERVICE_STATUS_FEEDBACK);//完成反馈状态
		serviceMapper.updateByPrimaryKeySelective(service);//更新数据库
		JsonResult jsonResult = new JsonResult();
		jsonResult.setData(service);
		logService.updateServiceLog(service, ServiceInterface.SERVICE_STATUS_FEEDBACK, user);
		return jsonResult;
	}

	/**
	 * 志愿者查看自己的接单记录
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping("vol/service/list")
	@AuthRequired
	public JsonResult volunteerAcceptList(@RequestBody Map<String, Object> reqMap, HttpServletRequest request) {
		User user = getCurrUser(request);
		PageView<Service> pageView = new PageView<>();
		pageView = pageView.startPage(reqMap);
		List<Service> list = serviceMapper.selectVolunteerMyService(user.getUserId(), pageView.getFirstResult(), pageView.getMaxresult());
		pageView.setRecords(list);
		pageView.setTotalrecord(serviceMapper.selectVolunteerMyServiceCount(user.getUserId()));//总记录数
		return JsonResult.success(pageView);
	}

	@RequestMapping("load/user")
	@AuthRequired
	public JsonResult loadUserInfo(HttpServletRequest request) {
		User user = (User) request.getAttribute("loginUser");
		User newUser = userMapper.selectByPrimaryKey(user.getUserId());
		Community community = communityMapper.selectByPrimaryKey(newUser.getCommunityId());
		newUser.setCommunity(community);
		JsonResult ret = new JsonResult();
		ret.setData(newUser);
		return ret;
	}

	@RequestMapping("logout")
	@AuthRequired
	public JsonResult logout(HttpServletRequest request) {
		User user = (User) request.getAttribute("loginUser");
		logService.userLogoutLog(user);
		JsonResult jsonResult = new JsonResult();
		return jsonResult;
	}

	@RequestMapping("community/all")
	public JsonResult allList() {
		JsonResult result = new JsonResult(true, "0", "查询成功");
		List<Community> list = communityMapper.selectAll();
		result.setData(list);
		return result;
	}
}
